<!DOCTYPE html>
<html>

<head>
    <!-- 页面meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>商品编辑</title>
    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
  
    <link rel="stylesheet" href="/plugins/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="/plugins/adminLTE/css/AdminLTE.css">
    <link rel="stylesheet" href="/plugins/adminLTE/css/skins/_all-skins.min.css">
    <link rel="stylesheet" href="/css/style.css">
	<script src="/plugins/jQuery/jquery-2.2.3.min.js"></script>
    <script src="/plugins/bootstrap/js/bootstrap.min.js"></script>
    
    <!-- 富文本编辑器 -->
	<link rel="stylesheet" href="/plugins/kindeditor/themes/default/default.css" />
	<script charset="utf-8" src="/plugins/kindeditor/kindeditor-min.js"></script>
	<script charset="utf-8" src="/plugins/kindeditor/lang/zh_CN.js"></script>

	<script type="text/javascript" src="/plugins/bootstrap-fileinput/js/fileinput.js"></script>
	<script type="text/javascript" src="/plugins/bootstrap-fileinput/js/locales/zh.js"></script>
	<link rel="stylesheet" type="text/css" href="/plugins/bootstrap-fileinput/css/fileinput.css">
<script>
	$(function (){
		itemcatList();
	})
	//一级联动
	function itemcatList(){
		$.ajax({
			url: "/goodsedit/itemcatList",
			data:{},
			async: false,
			dataType: "json",
			type: "post",
			success: function (result) {
				if (result.code == 10000){
					var list = result.data;
					var str = '';
					str+='<option value="-1">请选择</option>'
					for (var i = 0; i < list.length; i++){
						str+='<option value="'+list[i].id+'">'+list[i].name+'</option>'
					}
					$("#itemcat1").html(str);

				}
			},
			error: function (data) {
				alert("系统异常稍后重试")
			}
		})
	}

	//二级联动
	function selectTwo(id){
		$.ajax({
			url: "/goodsedit/itemcatList",
			data:{parentId:id},
			async: false,
			dataType: "json",
			type: "post",
			success: function (result) {
				if (result.code == 10000){
					var list = result.data;
					var str = '';
					str+='<option value="-1">请选择</option>'
					for (var i = 0; i < list.length; i++){
						str+='<option value="'+list[i].id+'">'+list[i].name+'</option>'
					}
					$("#itemcat2").html(str);
					$("#itemcat3").html("<option value=\"-1\">请选择</option>");
				}
			},
			error: function (data) {
				alert("系统异常稍后重试")
			}
		})
	}

	//三级联动
	function selectThree(id){
		$.ajax({
			url: "/goodsedit/itemcatList",
			data:{parentId:id},
			async: false,
			dataType: "json",
			type: "post",
			success: function (result) {
				if (result.code == 10000){
					var list = result.data;
					var str ='<option value="-1">请选择</option>'
					for (var i = 0; i < list.length; i++){
						$("#typeId").val(list[i].typeId);
						str+='<option value="'+list[i].id+'">'+list[i].name+'</option>'
					}
					$("#itemcat3").html(str);
				}
			},
			error: function (data) {
				alert("系统异常稍后重试")
			}
		})
	}

	//根据模板ID展示品牌
	function selectTypeTemplate(){
		var id = $("#typeId").val();
		$.ajax({
			url: "/goodsedit/selectTypeTemplate",
			data:{typeId:id},
			async: false,
			dataType: "json",
			type: "post",
			success: function (result) {
				if (result.code == 10000){
					var brandList = result.data.brandIds;

					var brandJson = JSON.parse(brandList);
					var str ='<option value="-1">请选择</option>';
					for (var i = 0;i<brandJson.length;i++){
						str+='<option value="' + brandJson[i].id + '">' + brandJson[i].text + '</option>'
					}
					$("#brandId").html(str);

					//扩展属性
					var cusu = result.data.customAttributeItems;
					var cusulist = JSON.parse(cusu);
					var str1 ='';
					for (var i =0;i<cusulist.length;i++){
						str1 += '<tr>'
						str1 += '<td>' + cusulist[i].text + '</td>'
						str1 += '<td>'
						str1 += '<input className="form-control" placeholder="扩展属性">'
						str1 += '</td>'
						str1 += '</tr>'
					}
					$("#customAttributeTable").html(str1);
				}
			},
			error: function (data) {
				alert("系统异常稍后重试")
			}
		})
	}

	//规格
	function spec(){
		var id = $("#typeId").val();
		$.ajax({
			url: "/goodsedit/selectSpec",
			data: {id: id},
			type: "post",
			dataType: "json",
			async: false,
			success: function (result) {
				console.log(result)
				if (result.code == 10000){
					var list = result.data;
					var str = '';
					for (var i = 0; i < list.length; i++){
						str += '<div name="specificationName">'
						str += '<div class="col-md-2 title">'+list[i].text+'</div>'

						str += '<div class="col-md-10 data">'
						var optionList = list[i].optionList;
						for (var j = 0;j<optionList.length;j++){
							str += '<span>'
							str += '<input onclick="checkSpec(this,\'' + list[i].text + '\',\'' + optionList[j].optionName + '\')" type="checkbox" >'+optionList[i].optionName
							str += '</span>'
						}
						str += '</div>'
						str += '</div>'
					}
					$("#specIdList").html(str);

					var str2 = '';
					str2 += '<tr>'
					str2 += '<td>4.0</td>'
					str2 += '<td>3G</td>'
					str2 += '<td>'
					str2 += '<input class="form-control" id="price" placeholder="价格">'
					str2 += '</td>'
					str2 += '<td>'
					str2 += '<input class="form-control" id="num" placeholder="库存数量">'
					str2 += '</td>'
					str2 += '<td>'
					str2 += '<input type="checkbox" id="box1">'
					str2 += '</td>'
					str2 += '<td>'
					str2 += '<input type="checkbox" id="box2">'
					str2 += '</td>'
					str2 += '</tr>'
					$("#specIdList2").html(str2);
				}else {
					$("#specIdList").html("");
				}
			}, error: function (result) {
				alert("系统异常")
			}
		})
	}

	var items=[];
	function checkSpec(event,name,value) {
		var obj = searchObjectByKey(items,'attributeName',name);
		if(obj != null){
			if ($(event).prop('checked')){//勾选
				obj.attributeValue.push(value);
			}else {//取消勾选
				obj.attributeValue.splice(obj.attributeValue.indexOf(obj),1)//从items中移除规格选项
				//如果规格选项中没哟数据
				if(obj.attributeValue.length == 0){
					//移除items中的数据
					items.splice(items.indexOf(obj),1)
				}
			}
		}else {
			//如果之前没有数据,items新加数据
			items.push({'attributeName':name,'attributeValue':[value]})
		}

	}

	//遍历组装用户勾选规格选项数据
	function searchObjectByKey(list,attributeName,attributeValue){
		for(var i=0;i<list.length;i++){
			//如果list中我们选择key存在
			if(list[i][attributeName] == attributeValue){
				return list[i];//返回当前对象
			}
		}
		//遍历结束后都不存在，返回null
		return null;
	}


		$(function (){
			$('#testfile').fileinput({
				language: 'zh',
				uploadUrl:'/file/upLoadFile',
				maxFileCount:5,
				enctype:"multipart/form-data",
				maxFileSize: 2048,
				allowedFileExtensions:["jsp","png","gif","jpg"],
				browseClass: 'btn btn-primary'
			});
			$("#testfile").on("fileuploaded",function (event,data,previewId,index){
				var imgUrl =data.response.data;
				$("[name=imageUrl]").val(imgUrl);
			})
		})


	function addInmage(){
		var img = document.getElementById("imageList");
		//创建一个tr标签
		var tr = document.createElement("tr");
		tr.innerHTML ="<tbody>" +
				"<td><span>"+ $('#color').val() + "</span></td>" +
				"<td><img src='"+$('#imageUrl').val() +"' width='100' height='100'></td>" +
				"<td>" +
				"<button type='button' class='form-control' className='btn btn-default' onclick='remove(this)' title='删除'>"+
				"<i className='fa fa-trash-o'></i> 删除 </button>" +
				"</td>" + "</tbody>"
		img.appendChild(tr);
	}

	//增加到页面展示的图片删除
	function remove(obj) {
		$(obj).parent().parent().remove();
	}



	function insert(){
	//goods表
		var category1Id = $("#itemcat1").val();//一级类目
		var category2Id = $("#itemcat2").val();//二级类目
		var category3Id = $("#itemcat3").val();//三级类目
		var typeTemplateId = $("#typeId").val();//分类模板ID
		var goodsName = $("#goodsName").val();//SPU名
		var brandId = $("#brandId").val();//品牌
		var caption = $("#caption").val();//副标题
		var price = $("#price").val();//商城价
		//goodsEdit表
		//商品简介的editor
		editor.sync()
		var introduction = $("[name=introduction]").val();//描述
		var packageList = $("#packageList").val();//包装列表
		var saleService = $("#saleService").val();//售后服务

		//itme表
		var price = $("#price").val();
		var num = $("#num").val();


		//图片添加
		var image = "";
		var trList = $("#imageList").find("tr")
		var i = 1;
		var optionList = [];
		trList.each(function (){
			var tdList = $(trList[i]).find("td");
			var colorName = $(tdList[0]).find("span").text();
			var imageName = $(tdList[1]).find("img").attr("src");
			image = imageName;
			var optionJson = {color:colorName,url:imageName};
			optionList.push(optionJson);
			i++;
		})
		var option = JSON.stringify(optionList);

		//扩展属性添加
		var cus = $("#customAttributeTable").find("tr")
		var customAttributeItem = []
		for (var i = 0; i < cus.length; i++) {
			var tds = $(cus[i]).find("td")
			var text = $(tds[0]).text()
			var input = $(tds[1]).find("input")
			var value = $(input).val()
			customAttributeItem.push({text : text, value : value})
		}
		var customAttributeItems = JSON.stringify(customAttributeItem);

		//规格转json
		var itemsJson = JSON.stringify(items)
		console.log(itemsJson)
		//spec{key:value}
		var  spec = "{\"机身内存\":\"16G\",\"网络\":\"联通4G\"}";

		//是否启用规格
		var is_enable_spec = $("#box1").prop("checked");
		var isEnableSpec = "0";
		if (is_enable_spec){
			isEnableSpec ="1";
		}

		//是否默认
		var is_delete = $("#box2").prop("checked");
		var isDelete = "0";
		if (is_delete){
			isDelete = "1";
		}

		$.ajax({
			url: "/goodsedit/addGoods",
			type: "post",
			dataType: "json",
			data: {
				//goods表增加
				auditStatus: 0,//审核状态
				category1Id: category1Id,//1级类目
				category2Id: category2Id,//2级类目
				category3Id: category3Id,//3级类目
				typeTemplateId: typeTemplateId,//分类模板Id
				goodsName: goodsName,//spu名
				brandId: brandId,//品牌
				caption: caption,//副标题
				price: price,//商城价
				isMarketable: 1,

				//goodsdesc表
				itemImages : option,//图片
				introduction: introduction,//描述
				packageList: packageList,//包装列表
				saleService: saleService,//售后服务
				customAttributeItems:customAttributeItems,//自定义扩展属性
				isEnableSpec: isEnableSpec,//是否启用规格
				isDelete: isDelete,//是否默认
				specificationItems:itemsJson,//规格结果集和

				//itme表
				spec:spec,//规格
				price: price,//商品价格
				num: num,//库存数量
				title:goodsName+spec,//商品标题
				image:image,//商品图片
				categoryid:typeTemplateId,//叶子
				itemSn:isEnableSpec,//是否启用规格
				status:1,//上下架
				stockCount:num,//现存库存
				costPirce:price,//成本价
				marketPrice:price,//市场价
				brand :brandId,//品牌

			},
			async: false,
			success: function (result) {
				if (result.code == 10000) {
					alert("增加成功")
				} else {
					alert(result.message);
				}
			},
			error: function (result) {
				console.log(result);
				alert("增加失败");
			}
		})
	}
</script>
      
    
    
</head>

<body class="hold-transition skin-red sidebar-mini" >

            <!-- 正文区域 -->
            <section class="content">

                <div class="box-body">

                    <!--tab页-->
                    <div class="nav-tabs-custom">

                        <!--tab头-->
                        <ul class="nav nav-tabs">                       		
                            <li class="active">
                                <a href="#home" data-toggle="tab">商品基本信息</a>                                                        
                            </li>   
                            <li >
                                <a href="#pic_upload" data-toggle="tab">商品图片</a>                                                        
                            </li>    
                            <li >
                                <a href="#customAttribute" data-toggle="tab">扩展属性</a>                                                        
                            </li>     
                            <li >
                                <a href="#spec" data-toggle="tab" >规格</a>                                                        
                            </li>                       
                        </ul>
                        <!--tab头/-->
						
                        <!--tab内容-->
                        <div class="tab-content">

                            <!--表单内容-->
                            <div class="tab-pane active" id="home">
                                <div class="row data-type">                                  
								   <div class="col-md-2 title">商品分类</div>
		                          
		                           	  <div class="col-md-10 data">
		                           	  	<table>
		                           	  		<tr>
		                           	  			<td>
		                           	  				<select class="form-control" id="itemcat1" onchange="selectTwo(this.value)"></select>
		                              			</td>
		                              			<td>
		                           	  				<select class="form-control  select-sm" id="itemcat2" onchange="selectThree(this.value)"></select>
		                              			</td>
		                              			<td>
		                           	  				<select class="form-control select-sm" id="itemcat3" onchange="selectTypeTemplate(this.value)"></select>
		                              			</td>
		                              			<td>
													模板ID:<input type="text" id="typeId" readonly>
		                              			</td>
		                           	  		</tr>
		                           	  	</table>
		                              	
		                              </div>	                              
		                          	  
									
		                           <div class="col-md-2 title">商品名称</div>
		                           <div class="col-md-10 data">
		                               <input type="text" class="form-control"  name="goodsName" id="goodsName"  placeholder="商品名称" value="">
		                           </div>
		                           
		                           <div class="col-md-2 title">品牌</div>
		                           <div class="col-md-10 data">
		                              <select class="form-control" id="brandId"></select>
		                           </div>
		
								   <div class="col-md-2 title">副标题</div>
		                           <div class="col-md-10 data">
		                               <input type="text" class="form-control" name="caption" id="caption"  placeholder="副标题" value="">
		                           </div>
		                           
		                           <div class="col-md-2 title">价格</div>
		                           <div class="col-md-10 data">
		                           	   <div class="input-group">
			                          	   <span class="input-group-addon">¥</span>
			                               <input type="text" class="form-control" name="price" id="price" placeholder="价格" value="">
		                           	   </div>
		                           </div>
		                           
		                           <div class="col-md-2 title editer">商品介绍</div>
                                   <div class="col-md-10 data editer">
                                       <textarea name="introduction" id="introduction" style="width:800px;height:400px;visibility:hidden;" ></textarea>
                                   </div>
		                           
		                           <div class="col-md-2 title rowHeight2x">包装列表</div>
		                           <div class="col-md-10 data rowHeight2x">
		                               
		                           	<textarea rows="4"  class="form-control" name="packageList" id="packageList"  placeholder="包装列表"></textarea>
		                           </div>
		                           
		                           <div class="col-md-2 title rowHeight2x">售后服务</div>
		                           <div class="col-md-10 data rowHeight2x">
		                               <textarea rows="4"  class="form-control"  name="saleService" id="saleService"  placeholder="售后服务"></textarea>
		                           </div>                        
                                  
                                    
                                </div>
                            </div>
                            
                            <!--图片上传-->
                            <div class="tab-pane" id="pic_upload">
                                <div class="row data-type">                                  
								 <!-- 颜色图片 -->
								 <div class="btn-group">
					                 <button type="button" class="btn btn-default" title="新建" data-target="#uploadModal"  data-toggle="modal"  ><i class="fa fa-file-o"></i> 新建</button>
                             		                 
					             </div>
								 
								 <table class="table table-bordered table-striped table-hover dataTable"  id="imageList">
					                    <thead>
					                        <tr>
					                            
											    <th class="sorting">颜色</th>
											    <th class="sorting">图片</th>
												<th class="sorting">操作</th>
							            </thead>
					                    <tbody>
<!--					                      <tr>					                           -->
<!--									            <td>-->
<!--									            	-->
<!--									            </td>-->
<!--									            <td>-->
<!--									           		<img alt="" src="" width="100px" height="100px">	            	 -->
<!--									            </td>-->
<!--												 <td> <button type="button" class="btn btn-default" title="删除" ><i class="fa fa-trash-o"></i> 删除</button></td> -->
<!--					                      </tr>-->
					                    </tbody>
								 </table> 
								  
                                </div>
                            </div>
                           
                           
                            <!--扩展属性-->
                            <div class="tab-pane" id="customAttribute">
<!--                                <div class="row data-type" >-->
									<table border="1" id="customAttributeTable">

									</table>
<!--	                                <div>-->
<!--		                                <div class="col-md-2 title">扩展属性1</div>-->
<!--				                        <div class="col-md-10 data">-->
<!--				                              <input class="form-control" placeholder="扩展属性1">	            	 -->
<!--				                        </div>-->
<!--	                                </div>       -->
<!--									<div>-->
<!--		                                <div class="col-md-2 title">扩展属性2</div>-->
<!--				                        <div class="col-md-10 data">-->
<!--				                              <input class="form-control" placeholder="扩展属性2">	            	 -->
<!--				                        </div>-->
<!--	                                </div>  									-->
<!--                                </div>-->
                            </div>
                      
                            <!--规格-->
                            <div class="tab-pane" id="spec">
                            	<div class="row data-type">
	                            	<div class="col-md-2 title">是否启用规格</div>
			                        <div class="col-md-10 data">
			                        	<input type="checkbox" name="check" onclick="spec()">
			                        </div>
                            	</div>
                            	<p>
                            	
                            	<div>
                            	
	                                <div class="row data-type" id="specIdList">

	                                </div>
	
	                                
	                                <div class="row data-type">
	                                	 <table class="table table-bordered table-striped table-hover dataTable">
						                    <thead>
						                        <tr>					                          
												    <th class="sorting">屏幕尺寸</th>
													<th class="sorting">网络制式</th>
												    <th class="sorting">价格</th>
												    <th class="sorting">库存</th>
												    <th class="sorting">是否启用</th>
												    <th class="sorting">是否默认</th>
											    </tr>
								            </thead>
						                    <tbody id="specIdList2" >
											  
						                    </tbody>
									 	</table>
								
	                                </div>
	                                
	                            </div>
                            </div>
                            
                        </div>
                        <!--tab内容/-->
						<!--表单内容/-->
							 
                    </div>
                 	
                 	
                 	
                 	
                   </div>
                  <div class="btn-toolbar list-toolbar">
				      <button class="btn btn-primary" onclick="insert()"><i class="fa fa-save"></i>保存</button>
				      <button class="btn btn-default" >返回列表</button>
				  </div>
			
            </section>
            
            
<!-- 上传窗口 -->
<div class="modal fade" id="uploadModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog" >
	<div class="modal-content">
		<div class="modal-header">
			<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
			<h3 id="myModalLabel">上传商品图片</h3>
		</div>
		<div class="modal-body">							
			
			<table class="table table-bordered table-striped">
		      	<tr>
		      		<td>颜色</td>
		      		<td><input  class="form-control" name="color" id="color" placeholder="颜色" >  </td>
		      	</tr>			    
		      	<tr>
		      		<td>商品图片</td>
		      		<td>
						<table>
							<tr>
								<td>
									<input type="text" name="imageUrl" id="imageUrl">
									<input type="file" id="testfile" name="image">
					            </td>
							</tr>						
						</table>
		      		</td>
		      	</tr>		      	
			 </table>				
			
		</div>
		<div class="modal-footer">
			<button class="btn btn-success"  data-dismiss="modal" onclick="addInmage()" aria-hidden="true">保存</button>
			<button class="btn btn-default" data-dismiss="modal" aria-hidden="true">关闭</button>
		</div>
	  </div>
	</div>
</div>

            
            <!-- 正文区域 /-->
<script type="text/javascript">

	var editor;
	KindEditor.ready(function(K) {
		editor = K.create('textarea[name="introduction"]', {
			allowFileManager : true
		});
	});

</script>
       
</body>

</html>